const database = require('./database');
const axios = require('axios');

class ApiKeyModel {
  // 获取数据库连接池
  getPool() {
    const pool = database.getPool();
    if (!pool) {
      throw new Error('数据库连接池未初始化');
    }
    return pool;
  }

  // 验证API密钥数据
  validateApiKeyData(key, provider, endpoint) {
    const errors = [];
    
    if (!key || typeof key !== 'string' || key.trim() === '') {
      errors.push('API密钥不能为空');
    }
    
    if (!provider || typeof provider !== 'string' || provider.trim() === '') {
      errors.push('模型ID不能为空');
    }
    
    if (!endpoint || typeof endpoint !== 'string' || endpoint.trim() === '') {
      errors.push('API地址不能为空');
    }
    
    try {
      new URL(endpoint); // 验证URL格式
    } catch (error) {
      errors.push('API地址格式无效');
    }
    
    return errors;
  }

  /**
   * 添加API密钥
   * @param {string} key - API密钥
   * @param {string} provider - 提供商标识
   * @param {string} endpoint - API端点地址
   * @param {string} modelName - 模型名称（可选）
   * @returns {Promise<number>} - 返回新添加的API密钥ID
   */
  async addApiKey(key, provider, endpoint, modelName = '') {
    console.log('添加API密钥:', { key, provider, endpoint, modelName });
    
    // 验证参数
    if (!this.validateApiKeyData(key, provider, endpoint)) {
      throw new Error('API密钥验证失败');
    }
    
    // 清理数据
    key = key.trim();
    provider = provider.trim();
    endpoint = endpoint.trim();
    modelName = modelName ? modelName.trim() : '';

    try {
      const pool = this.getPool();
      console.log('获取连接池成功, 数据库信息:', pool.pool.config.connectionConfig.database);

      // 检查表是否存在
      const [tables] = await pool.query('SHOW TABLES LIKE ?', ['api_keys']);
      console.log('检查表是否存在:', tables.length > 0 ? '存在' : '不存在');
      
      if (tables.length === 0) {
        console.log('api_keys表不存在，创建表');
        await pool.query(`
          CREATE TABLE IF NOT EXISTS api_keys (
            id INT AUTO_INCREMENT PRIMARY KEY,
            \`key\` TEXT NOT NULL,
            provider VARCHAR(50) NOT NULL,
            endpoint VARCHAR(255) NOT NULL,
            modelName VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
          )
        `);
        console.log('表创建成功');
      } else {
        // 检查并修改key字段的类型为TEXT（如果需要）
        try {
          console.log('检查key字段类型');
          await pool.query(`
            ALTER TABLE api_keys 
            MODIFY COLUMN \`key\` TEXT NOT NULL
          `);
          console.log('key字段已更新为TEXT类型');
        } catch (alterError) {
          console.log('修改字段类型时出错，可能字段已经是TEXT类型:', alterError.message);
        }
      }

      // 检查是否已存在相同的配置
      const [existing] = await pool.query(
        'SELECT id FROM api_keys WHERE `key` = ? AND provider = ? AND endpoint = ?',
        [key, provider, endpoint]
      );
      
      console.log('检查是否存在:', existing);
      
      // 如果不存在相同配置，则添加
      if (existing.length === 0) {
        console.log('执行SQL: INSERT INTO api_keys (`key`, provider, endpoint, modelName) VALUES (?, ?, ?, ?)');
        console.log('参数:', [key, provider, endpoint, modelName || null]);
        
        const [result] = await pool.query(
          'INSERT INTO api_keys (`key`, provider, endpoint, modelName) VALUES (?, ?, ?, ?)',
          [key, provider, endpoint, modelName || null]
        );

        console.log('API密钥添加成功:', result.insertId);
        
        // 验证插入是否成功
        const [verification] = await pool.query('SELECT * FROM api_keys WHERE id = ?', [result.insertId]);
        if (verification.length === 0) {
          throw new Error('API密钥添加后无法验证');
        }
        console.log('验证成功:', verification[0]);
        
        return result.insertId;
      } else {
        throw new Error('该API配置已存在');
      }
    } catch (dbError) {
      console.error('数据库操作失败:', dbError);
      throw new Error(`数据库操作失败: ${dbError.message}`);
    }
  }

  // 获取所有API密钥
  async getAllApiKeys() {
    try {
      const pool = this.getPool();
      console.log('获取所有API密钥...');
      
      // 检查表是否存在
      const [tables] = await pool.query('SHOW TABLES LIKE ?', ['api_keys']);
      if (tables.length === 0) {
        console.log('api_keys表不存在');
        return [];
      }
      
      const [rows] = await pool.query('SELECT * FROM api_keys ORDER BY created_at DESC');
      console.log(`获取到 ${rows.length} 条API密钥记录`);
      return rows;
    } catch (error) {
      console.error('获取API密钥失败:', error);
      throw error;
    }
  }

  // 测试API配置
  async testApiConfig(key, provider, endpoint, modelName = '') {
    try {
      console.log('测试API配置:', { key, provider, endpoint, modelName });
      
      // 数据验证
      const errors = this.validateApiKeyData(key, provider, endpoint);
      if (errors.length > 0) {
        return { 
          success: false, 
          message: errors.join(', ')
        };
      }

      // 清理并格式化endpoint，确保它是以/结尾的有效URL
      let cleanEndpoint = endpoint.trim();
      if (!cleanEndpoint.endsWith('/')) {
        cleanEndpoint += '/';
      }

      // 构建完整的API URL (大多数AI API都使用v1/chat/completions路径)
      const apiUrl = `${cleanEndpoint}v1/chat/completions`;
      console.log('测试API URL:', apiUrl);

      // 使用实际模型名称或提供的provider
      const modelToUse = modelName || provider;

      // 创建测试请求数据
      const requestData = {
        model: modelToUse,
        messages: [
          { role: "user", content: "你好，这是一条测试消息，请回复'API连接测试成功'" }
        ],
        temperature: 0.7,
        max_tokens: 50
      };

      // 创建测试请求配置
      const config = {
        headers: {
          'Authorization': `Bearer ${key}`,
          'Content-Type': 'application/json'
        },
        timeout: 15000 // 15秒超时
      };

      console.log('发送测试请求数据:', requestData);
      
      // 发送测试请求
      const response = await axios.post(apiUrl, requestData, config);

      // 检查响应
      if (response.status >= 200 && response.status < 300) {
        console.log('API测试成功, 状态码:', response.status);
        
        if (response.data && response.data.choices && response.data.choices.length > 0) {
          const content = response.data.choices[0].message?.content || '';
          return { 
            success: true, 
            message: `测试成功，模型响应: "${content.substring(0, 30)}${content.length > 30 ? '...' : ''}"`,
            data: {
              model: response.data.model,
              usage: response.data.usage
            }
          };
        } else {
          return { 
            success: true, 
            message: '测试成功，但响应格式异常',
            data: response.data
          };
        }
      } else {
        throw new Error(`API返回错误状态码: ${response.status}`);
      }
    } catch (error) {
      console.error('API测试失败:', error);
      
      let errorMessage = '测试失败';
      
      // 提取更有用的错误信息
      if (error.response) {
        // 服务器返回了错误状态码
        const statusCode = error.response.status;
        const errorData = error.response.data;
        
        if (statusCode === 401) {
          errorMessage = 'API密钥无效或未授权';
        } else if (statusCode === 404) {
          errorMessage = 'API地址错误或endpoint不存在';
        } else if (statusCode === 429) {
          errorMessage = 'API请求次数超限或达到速率限制';
        } else if (statusCode >= 500) {
          errorMessage = 'API服务器内部错误';
        }
        
        // 尝试从错误响应中提取详细信息
        if (errorData && errorData.error) {
          if (typeof errorData.error === 'string') {
            errorMessage += `: ${errorData.error}`;
          } else if (errorData.error.message) {
            errorMessage += `: ${errorData.error.message}`;
          } else if (errorData.error.type) {
            errorMessage += `: ${errorData.error.type}`;
          }
        }
      } else if (error.code === 'ECONNABORTED') {
        errorMessage = '连接超时，请检查API地址或网络状态';
      } else if (error.code === 'ENOTFOUND') {
        errorMessage = '无法解析API地址，请检查URL是否正确';
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      return { 
        success: false, 
        message: errorMessage,
        error: process.env.NODE_ENV === 'development' ? error.toString() : undefined
      };
    }
  }

  // 删除API密钥
  async deleteApiKey(id) {
    console.log(`删除API密钥 - 开始，ID: ${id}`);
    
    try {
      // 获取数据库连接池
      const pool = this.getPool();
      if (!pool) {
        throw new Error('数据库连接池未初始化');
      }
      
      // 检查API密钥是否存在
      const [existingKey] = await pool.query('SELECT * FROM api_keys WHERE id = ?', [id]);
      
      if (existingKey.length === 0) {
        throw new Error(`未找到ID为 ${id} 的API密钥`);
      }
      
      // 执行删除
      const [result] = await pool.query('DELETE FROM api_keys WHERE id = ?', [id]);
      
      if (result.affectedRows === 0) {
        throw new Error(`删除API密钥失败，ID: ${id}`);
      }
      
      console.log(`删除API密钥 - 成功，ID: ${id}`);
      return true;
    } catch (error) {
      console.error(`删除API密钥 - 失败，ID: ${id}:`, error);
      throw error;
    }
  }
}

module.exports = new ApiKeyModel(); 